package com.lzh.runke.core.web_base.helper;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description: 导出CSV文件
 * @Author: LiuZiHao
 * @Date: 2022/5/24 17:56
 */
@Slf4j
public class CSVHelper {
    /**
     * @return byte[]
     * @Author hutingrui
     * @Description 写CSV文件并转换为字节流
     * @Date 14:26 2021/3/24
     * @Param [headers, dataList]
     **/
    public static byte[] writeAsBytes(Iterable<?> data, String... headers) {
        byte[] bytes = new byte[0];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8);
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        CSVPrinter csvPrinter = null;
        try {
            byteArrayOutputStream.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            //创建csvPrinter并设置表头
            csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader(headers));
            //写数据
            csvPrinter.printRecords(data);
            csvPrinter.flush();
            bytes = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name()).getBytes();
        } catch (IOException e) {
            log.error("writeCsv IOException:{}", e.getMessage(), e);
        } finally {
            try {
                if (csvPrinter != null) {
                    csvPrinter.close();
                }
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (outputStreamWriter != null) {
                    outputStreamWriter.close();
                }
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
            } catch (IOException e) {
                log.error("iostream close IOException:{}", e.getMessage(), e);
            }
        }
        return bytes;
    }

    /**
     * @return void
     * @Author hutingrui
     * @Description 设置下载响应
     * @Date 14:28 2021/3/24
     * @Param [fileName, bytes, response]
     **/
    public static ResponseEntity<byte[]> writeAsHttpResponse(String fileName, Iterable<?> data, String... header) {
        try {
            HttpHeaders headers = new HttpHeaders();
            byte[] bytes = writeAsBytes(data, header);
            try {
                if (StringUtils.isNotBlank(fileName)) {
                    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
                }
            } catch (UnsupportedEncodingException ex) {
                log.error("导出失败：编码异常");
                log.error(ex.getMessage());
            }
            headers.set("Character-Encoding", StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            List<String> accessControlExposeHeaders = Lists.newArrayListWithExpectedSize(1);
            String accessControlExposeHeader = "Content-Disposition";
            accessControlExposeHeaders.add(accessControlExposeHeader);
            headers.setAccessControlExposeHeaders(accessControlExposeHeaders);
            return new ResponseEntity(bytes, headers, HttpStatus.CREATED);
        } catch (Exception e) {
            log.error("iostream errorL{}", e.getMessage(), e);
        }
        return null;
    }
}
